var access = "public"; 
var convertPDF = false;
var index = false;
var tags;

// Create "Uppladdade filer" folder in userhome.
uppladdat = userhome.childByNamePath("Uppladdade filer");
if (uppladdat == null && userhome.hasPermission("CreateChildren")) {
  	// create the folder for the first time
   	uppladdat = userhome.createFolder("Uppladdade filer");
}

// locate mandatory fields
for each (field in formdata.fields) {   
       
   	// mandatory fields
   	if (field.name == "file" && field.isFile) {
	   	filename = field.filename;
		content = field.content;
	}

   	// omnifind indexing checkbox 
   	if(field.name == "omnifind" && field.value == "true"){
      	index = true;
   	}

   	// accesszone checkbox
   	if(field.name == "accesszone"){
		access = field.value;
   		model.access = access;
   	}
	
   	// tags
   	if(field.name == "tags"){
		model.tags = field.value.split(", ");
   	}

	if(field.name == "convert_pdf"){
    	convertPDF = true;
   	}

   	// available until checkbox here.........
		
}

// ensure mandatory file attributes have been located
if (filename == undefined || content == undefined) {
   	status.code = 400;
   	status.message = "Uploaded file cannot be located in request";
   	status.redirect = true;
} else {
   	// create document in vgr folder for uploaded file
   	while(uppladdat.childByNamePath(filename) != null){
	 	filename = "_" + filename;   
   	}
   
   	upload = uppladdat.createFile(filename);
   	upload.specializeType("vgr:doc");
   	upload.properties.content.write(content);
   	upload.properties.encoding = "UTF-8";

   	// set access rights... (user, intranet, (all??))
	upload.setPermission("Read"); // on intranet/public
	upload.setPermission("Read", "guest"); 

   	model.upload = upload;

	// set expires aspect

   // run action for omnifind indexing (ScriptAction API)

   // convert to PDF
   /*pdfTransformation = upload.transformDocument("application/pdf", uppladdat);
      
   if (pdfTransformation == null) {
      // Create error text
   } else {
//      upload.createAssociation(pdfTransformation, "vgr:pdfTransformation");
//      upload.save();
   }
	*/
   // create thumbnails
   thumbnailNames = upload.getThumbnailDefintions();
   
   var thumbnails = new Array{};
   
   j = 0;
   for (var i = 0; i < thumbnailNames.length; i++) {
     thumbnailName = thumbnailNames[i];
     if(thumbnailName != "" && thumbnailService.isThumbnailNameRegistered(thumbnailName)) { 
        thumbnails[j] = upload.createThumbnail(thumbnailName);
        j++;
     }
   }

/*<#list thumbnailNames as thumbnail>*/
	model.thumbnails = thumbnails;

	// handle mail sending list (maybe start a workflow?)
  	model.dbid = "" + upload.properties["sys:node-dbid"];
 	upload.save();
}